using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using HappySprite;
using HappySprite.Simulation;

namespace HappyInvaders
{
    class PlayerEntity : Entity
    {
        public PlayerEntity()
        {
            Item.CollisionShape = Box.CreateFromSize(Constants.PlayerWidth, Constants.PlayerHeight);
            Item.CollisionGroup = Constants.PlayerGroup;
            Item.CollisionMask = Constants.BombGroup | Constants.InvaderGroup;

            Item.SetWorldLimits(Constants.PlayerMinX, 0f, Constants.PlayerMaxX, Constants.WorldHeight);

            // Handle world limits
            Item.WorldLimitsExceeded += Item.ClampToWorldLimits;

            // Handle collision
            Item.Collision += delegate(CollisionEventArgs e)
            {
                Owner.CreateExplosion(Position);
                Remove();

                // Force end of game if collide with invader
                if (e.Other.Tag is InvaderEntity)
                {
                    Owner.Lives = 0;
                }
            };
        }

        internal override void OnAdd()
        {
            Owner.Player = this;
        }

        internal override void OnRemove()
        {
            Owner.Player = null;
        }

        public void HandlePlayerInput(PlayerInput playerInput)
        {
            // Move the player
            Vector2 velocity = Vector2.Zero;

            if (playerInput != null)
            {
                if (playerInput.MoveLeft) velocity.X -= Constants.PlayerSpeed;
                if (playerInput.MoveRight) velocity.X += Constants.PlayerSpeed;
            }

            Item.Velocity = velocity;

            // Check for player fire
            if (playerInput.Fire)
            {
                if (Owner.BulletCount > 0 || Owner.ZapCount > 0)
                    return;

                // Set the bullet position right above the player
                Vector2 position = Position;
                position.Y += Constants.PlayerHeight;
                Owner.CreateBullet(position);
            }
        }
    }
}
